'use strict';

var http = require('http');
var connect = require('connect');
var urllib = require('urllib');
var staticServe = require('serve-static');
var finalhandler = require('finalhandler');
var debug = require('debug')('proxy');
var config = require('./config');
var bodyParser = require('body-parser');

var app = connect();
var stServe = staticServe('./app', {index: ['index.html', 'index.htm']});

app.use(bodyParser.urlencoded({extended: false}));
// API 代理
app.use('/proxy', function(req, res) {
  var done = finalhandler(req, res);
  var url = config.hostDomain + req.url.replace(/^proxy/, '').replace(/\/+/, '/');
  debug(url);
  var options = {
    timeout: config.httpTimeout,
    method: req.method,
    headers: req.headers,
    data: req.body
  };
  debug(options);
  urllib.request(url, options, function(error, data, result) {
    if (error) {
      debug(error);
      return done(error);
    }
    debug(data.toString());
    debug(result);
    res.end(data);
  });
});

app.use(function(req, res) {
  var done = finalhandler(req, res);
  stServe(req, res, done);
});

http.createServer(app).listen(config.port);
console.log('Server listen on port %d.', config.port);
